<template>
  <Form ref="bindForm" class="xtx-form" :validation-schema="schema" v-slot="{ errors }" autocomplete="off">
    <div class="user-info">
      <img :src="avatar" alt="" />
      <p>Hi，{{ nickname }} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field :class="{ err: errors.mobile }" name="mobile" v-model="form.mobile" class="input" type="text"
          placeholder="绑定的手机号" />
        <div v-if="errors.mobile" class="error"><i class="iconfont icon-warning" />{{ errors.mobile }}</div>
      </div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field :class="{ err: errors.code }" name="code" v-model="form.code" class="input" type="text"
          placeholder="短信验证码" />
        <button ref="codeCom" @click.prevent="send" class="code">
          {{ time === 0 ? '发送验证码' : `${time}s后发送` }}
        </button>
        <div v-if="errors.code" class="error"><i class="iconfont icon-warning" />{{ errors.code }}</div>
      </div>
    </div>
    <a @click="bind" href="javascript:;" class="submit">立即绑定</a>
  </Form>
</template>

<script setup>
import QC from 'qc'
import { reactive, ref, defineProps, onUnmounted } from 'vue'
import { userQQBindLogin, userQQBindCode } from '@/api/login'
import { Form, Field } from 'vee-validate'
// 从配置选项中导入公用的验证规则
import { myFormValidate } from '@/config'
import Message from '@/components/library/message'
import { useIntervalFn } from '@vueuse/core'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
const store = useStore()
const route = useRoute()
const router = useRouter()
const props = defineProps({
  unionId: {
    type: String,
    default: ''
  }
})
// 定义用户的头像和昵称
const nickname = ref('null')
const avatar = ref('null')
if (QC.Login.check()) {
  // 获取用户在QQ服务器的头像和昵称
  QC.api('get_user_info').success(res => {
    avatar.value = res.data.figureurl_2
    nickname.value = res.data.nickname
  })
}
// 定义表单数据
const form = reactive({
  mobile: null,
  code: null
})
// 定义本表单的验证规则
const schema = {
  mobile: myFormValidate.mobile,
  code: myFormValidate.code
}
const bindForm = ref(null)
// 登录时发送短信验证码
const codeCom = ref(null)
const time = ref(0)
// 定时器的处理函数
// pause 暂停 resume 开始
// useIntervalFn(回调函数,执行间隔,是否立即开启)
const { pause, resume } = useIntervalFn(() => {
  // 定时器的业务
  time.value--
  if (time.value <= 0) {
    //  停止定时器
    pause()
    // 发送按钮可用
    codeCom.value.disabled = false
    time.value = 0
  }
}, 1000, false)
// 组件销毁时，清除定时器
onUnmounted(() => {
  pause()
})

// 发送登录验证码
function send() {
  // 需要对用户填写的手机号码做校验
  //  由于点击发送验证码的行为，并不需要手机号码选项失去焦点或者是提交表单时触发，主动触发表单的验证规则
  const mobileValid = schema.mobile(form.mobile)
  if (mobileValid === true) {
    // 代表是标准的手机号码,可以发送短信
    userQQBindCode(form.mobile).then(() => {
      // 设置倒计时时间
      time.value = 60
      // 禁用按钮
      codeCom.value.disabled = true
      // 开启定时器
      resume()
      // 提示
      Message({ type: 'success', text: '短信验证码发送成功' })
    }).catch(e => {
      Message({ type: 'error', text: e.response.data.message || '短信发送失败' })
    })
  } else {
    // 失败，使用vee的错误函数显示错误信息 setFieldError(字段,错误信息)
    bindForm.value.setFieldError('mobile', mobileValid)
  }
}
// 绑定账号
async function bind() {
  const valid = await bindForm.value.validate()
  if (valid) {
    try {
      const { result } = await userQQBindLogin({ unionId: props.unionId, mobile: form.mobile, code: form.code })
      // 1. 存储用户信息
      const { id, account, avatar, mobile, nickname, token } = result
      store.commit('user/setUser', { id, account, avatar, mobile, nickname, token })
      // 合并购物车
      store.dispatch('cart/mergeCart').then(() => {
        // 2. 跳转到来源页或者首页
        router.push((route.query.redirectUrl && decodeURIComponent(route.query.redirectUrl)) || store.state.user.currentPath || '/')
        // 3. 成功提示
        Message({ type: 'success', text: '账号绑定成功' })
      })
    } catch (err) {
      Message({ type: 'error', text: '账号绑定失败' })
    }
  } else {
    Message({ type: 'error', text: '校验失败', time: 5000 })
  }
}
</script>

<style scoped lang='less'>
.user-info {
  width: 320px;
  height: 70px;
  margin: 0 auto;
  display: flex;
  background: #f2f2f2;
  align-items: center;
  padding: 0 10px;
  margin-bottom: 25px;

  img {
    background: #f2f2f2;
    width: 50px;
    height: 50px;
  }

  p {
    padding-left: 10px;
  }
}

.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 120px;
  height: 50px;

  &:hover {
    cursor: pointer;
  }
}
</style>